package com.test1;

import android.graphics.Canvas;

import java.util.ListIterator;
import java.util.LinkedList;
public class GameLayer implements GameListener {
	public static int bottom = 0;
	public static int game = 0;
	public static int pop = 0;
	public static int top = 0;
	
	private LinkedList< GameObject > children = new LinkedList< GameObject >();
	public void draw( Canvas canvas ){
		ListIterator< GameObject > it = children.listIterator();
		while( it.hasNext() ){
			GameObject child = it.next();
			child.OnDraw( canvas, child.x, child.y );
		}
	}
	
	public void update( long e ){
		ListIterator< GameObject > it = children.listIterator();
		while( it.hasNext() ){
			GameObject child = it.next();
			child.onUpdate( e );
		}
	}
	
	public int getNextHightDepth(){
		int size = children.size();
		if( size == 0 ){
			return 1;
		}
		return children.get( size - 1 ).depth + 1;
	}
	
	public final void add( GameObject obj ){
		obj.depth = this.getNextHightDepth();
		children.add( obj );
		obj.father = this;
	}
	
	public final void add( GameObject obj, int depth ){
		if( depth < 0 ){
			 this.add( obj );
			 return;
		}
		obj.father = this;
		obj.depth = depth;
		ListIterator< GameObject > it = children.listIterator();
		while( it.hasNext() ){
			GameObject child = it.next();
			if( child.depth > depth ){
				it.add( obj );
				return;
			}
		}
		it.add( obj );
	}
	
	public void remove( GameObject child ){
		children.remove( child );
		child.father = null;
		Pool.push( child );
	}
	
	public void top( GameObject child ){
		children.remove( child );
		children.add( child );
	}
	
	public void bottom( GameObject child ){
		children.remove( child );
		children.add( 0, child );
	}

	public void onPress( GameEvent event ) {
		// TODO Auto-generated method stub
		ListIterator< GameObject > it = children.listIterator();
		int x, y;
		while( it.hasNext() ){
			GameObject obj = it.next();
			if( event.x >= obj.x && event.x < obj.x+obj.w  && event.y >= obj.y && event.y <= obj.y+obj.h){
				x = event.x ;
				y = event.y ;
				event.x = event.x - obj.x;
				event.y = event.y - obj.y;
				obj.onPress( event );
				event.x = x;
				event.y = y;
			}
		}
	}

	public void onRelease(GameEvent event) {
		// TODO Auto-generated method stub
		
	}

	public void onClick(GameEvent event) {
		// TODO Auto-generated method stub
		
	}

	public void onDragBegin(GameEvent event) {
		// TODO Auto-generated method stub
		
	}

	public void onDrag(GameEvent event) {
		// TODO Auto-generated method stub
		
	}

	public void onDragEnd(GameEvent event) {
		// TODO Auto-generated method stub
		
	}
}
